package com.sjsu.aws.primitve.client.doublebarrier;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import com.sjsu.aws.doublebarrier.DoubleBarrier;
import com.sjsu.aws.doublebarrier.DoubleBarrierServiceImpl;
import com.sjsu.aws.utils.TimeUtil;

/**
 * 
 * @author Pawar Deepali
 * 
 */
public class RenewEndTimeThreadDoubleBarrier {
	
	private final static ScheduledExecutorService	scheduler	= Executors
	                                                                  .newScheduledThreadPool(1);
	
	public static void main(String[] args) throws Exception {
		long pollingPeriod = 10000;
		String participantId = "p16";
		startPolling(pollingPeriod, participantId);
	}
	
	public static void startPolling(long pollingPeriod, String participantId)
	        throws Exception {
		System.out.println("Start Polling1");
		DoubleBarrierServiceImpl doubleBarrierServiceImpl = new DoubleBarrierServiceImpl();
		System.out.println("Start Polling2");
		pollDB(pollingPeriod, participantId, doubleBarrierServiceImpl);
	}
	
	public static void pollDB(final long pollingPeriod, final String participantId,
	        final DoubleBarrierServiceImpl doubleBarrierServiceImpl) {
		
		final Runnable watcher = new Runnable() {
			public void run() {
				System.out.println("Polling database...");
				DoubleBarrier db = new DoubleBarrier();
				db.setParticipantId(participantId);
				db.setEndTimestamp(TimeUtil.getEndTime(pollingPeriod));
				try {
					doubleBarrierServiceImpl.renewEphemeralMembership(db);
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(
					        "Error in ephemeral Thread, Error message : "
					                + e.getMessage());
				}
				
			}
		};
		
		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
		        watcher, 0, pollingPeriod, MILLISECONDS);
	}
}